﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Util;
using IntroduceCompany.Singleton;
using System.IO;
using IntroduceCompany.Models;
using System.Data.Linq;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [CheckModule(ConstantClass.Backend_Album_MenuID)]
    public class AlbumController : BaseController
    {
  #region BackEnd_Album
        /// <summary>
        /// get albums to view
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult AlbumList()
        {
            string languageID = ConstantClass.markViewAllLanguage;
            if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
            {
                languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
            }

            string amount = ConstantClass.defaultAmount;
            if (Request.Cookies[ConstantClass.cooAmount] != null)
            {
                amount = Request.Cookies[ConstantClass.cooAmount].Value;
            }

            ViewData["amountList"] = new SelectList(new[] { "10", "25", "50", "100", "250" }
                .Select(x => new { value = x, text = x }),
                "value", "text", amount);

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);

            return View("/Views/Backend/Album/AlbumList.aspx", DataSingleton.GetAlbumModels().GetAlbums(languageID, amount));
           // return View("/Views/Backend/Album/AlbumList.aspx", DataSingleton.GetAlbumModels().GetAlbums(languageID));
        }

        /// <summary>
        /// in backend, get a specific amount of articles
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult ChangeAmountToShow(String amountList)
        {
            if (Request.Cookies[ConstantClass.cooAmount] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooAmount, amountList);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddHours(2);
            }
            else
            {
                Response.Cookies[ConstantClass.cooAmount].Value = amountList;
            }

            return RedirectToAction("AlbumList", "Album");
        }


        /// <summary>
        /// Change Album Status that is visible or invisible
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="albumVisible"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult ChangeAlbumVisible(int albumID, bool albumVisible)
        {
            if (ModelState.IsValid)
            {
                DataSingleton.GetAlbumModels().ChangeAlbumVisible(albumID, albumVisible);
            }
            return RedirectToAction("AlbumList", "Album");
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult AlbumCreate()
        {
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
            return View("/Views/Backend/Album/AlbumCreate.aspx");
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt, Order = 2)]
        public ActionResult AlbumCreate(AlbumView _NewOneAlbum, HttpPostedFileBase uploadFile)
        {
            int albumMaxID = 0;
            _NewOneAlbum.Username = HttpContext.User.Identity.Name;// thay doi khi thực hiện chức năng log in
            string newImageName = "";
            if (uploadFile != null && uploadFile.ContentLength > 0 && _NewOneAlbum.AlbumTitle != null && _NewOneAlbum.AlbumTitle.ToString() !="")
            {
                newImageName = ThumbnailClass.ImageNameStandardization(_NewOneAlbum.AlbumTitle);
                string fileExtension = Path.GetExtension(uploadFile.FileName).ToLower().Trim();
                newImageName = newImageName + "-" + DateTime.Now.Ticks;
                newImageName = newImageName.Length > 290 ? newImageName.Substring(0, 70) : newImageName;
                _NewOneAlbum.AlbumPhoto = newImageName + fileExtension;

            }
            if (ModelState.IsValid)
            {
                albumMaxID = DataSingleton.GetAlbumModels().AlbumCreate(_NewOneAlbum);
                DataSingleton.GetAlbumModels().Album_L_Create(albumMaxID, _NewOneAlbum.LanguageID, _NewOneAlbum.AlbumTitle, _NewOneAlbum.AlbumDescription);

                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    //Upload Image article and create some folders
                    DataSingleton.GetGeneralModels().UploadImageAlbum(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString()
                        , "Image/Album/"), albumMaxID, "", newImageName, ConstantClass._albumThumbnailHeight);
                }
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
                return RedirectToAction("Edit", "Album", new { albumID = albumMaxID, languageID = _NewOneAlbum.LanguageID });
            }
            else
            {
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName");
                return View("/Views/Backend/Album/AlbumCreate.aspx");
            }
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        [ValidateInput(false)]
        [ActionName("Edit")]
        public ActionResult AlbumEdit(int albumID, String languageID)
        {
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);//languageID
            AlbumView oneAlbumView = DataSingleton.GetAlbumModels().GetAlbumByAlbumIDAndLanguageID(albumID, languageID);
          //  Session["AlbumLanguageRecord"] = "true";
            if (oneAlbumView == null)
            {
                oneAlbumView = new AlbumView();
                Album album = DataSingleton.GetAlbumModels().GetAlbumByID(albumID);
                oneAlbumView.AlbumID = album.AlbumID;
                oneAlbumView.AlbumPhoto = album.AlbumPhoto;
                oneAlbumView.FullName = album.Administrator.FullName;
                oneAlbumView.AlbumDate = album.AlbumDate;
            }
            return View("/Views/Backend/Album/AlbumEdit.aspx", oneAlbumView);
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        [HttpPost, ValidateInput(false)]
        [ValidateAntiForgeryToken(Salt = AntiKey.EditSalt, Order = 2)]
        public ActionResult AlbumEdit(AlbumView _EditedAlbumView, HttpPostedFileBase uploadFile)
        {
            string username = HttpContext.User.Identity.Name;
            _EditedAlbumView.Username = username;
            AlbumView oneAlbumView = DataSingleton.GetAlbumModels().GetAlbumByAlbumIDAndLanguageID(_EditedAlbumView.AlbumID, _EditedAlbumView.LanguageID);

            if (uploadFile != null && uploadFile.ContentLength > 0 && _EditedAlbumView.AlbumTitle != null && _EditedAlbumView.AlbumTitle.ToString() != "")
            {
                //Upload Image album
                string newImageName = ThumbnailClass.ImageNameStandardization(_EditedAlbumView.AlbumTitle);
                string fileExtension = Path.GetExtension(uploadFile.FileName).ToLower().Trim();
                newImageName = newImageName + "-" + DateTime.Now.Ticks;

                _EditedAlbumView.AlbumPhoto = DataSingleton.GetGeneralModels().UploadImageAlbum(uploadFile, Path.Combine(Request.PhysicalApplicationPath.ToString()
                    , "Image/Album/"), _EditedAlbumView.AlbumID, _EditedAlbumView.AlbumPhoto, newImageName, ConstantClass._albumThumbnailHeight);

                DataSingleton.GetAlbumModels().UpdateAlbumThumbnail(_EditedAlbumView);
            }

            if (oneAlbumView != null)// the album has this language so update only
            {
                if (ModelState.IsValid && DataSingleton.GetAlbumModels().AlbumEdit(_EditedAlbumView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("Notice", "Thông tin đã được cập nhật.");
                }
                else 
                {
                    ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thông tin.");
                }
            }
            else// the album do not has this language so insert new language
            {
                if (ModelState.IsValid && DataSingleton.GetAlbumModels().Album_L_Create(_EditedAlbumView.AlbumID, _EditedAlbumView.LanguageID,
                    _EditedAlbumView.AlbumTitle, _EditedAlbumView.AlbumDescription))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("Notice", "Album đã được cập nhật thêm ngôn ngữ mới.");
                }
                else
                {
                    ModelState.AddModelError("Notice", "Có lỗi khi cập nhật thêm ngôn mới.");
                }
            }
            
            _EditedAlbumView.AlbumDate = DateTime.Now;
            _EditedAlbumView.FullName = DataSingleton.GetInstance().Administrators.SingleOrDefault(u => u.UserName == username).FullName;
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", _EditedAlbumView.LanguageID);
            return View("/Views/Backend/Album/AlbumEdit.aspx", _EditedAlbumView);
        }


        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult AlbumDelete(int albumID)
        {
            DataSingleton.GetAlbumModels().AlbumDelete(albumID, Path.Combine(Request.PhysicalApplicationPath.ToString(), "Image/Album/"));
            return RedirectToAction("AlbumList", "Album");
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult AlbumDetail(int albumID, String languageID)
        {
            Session["LanguageID_AlbumDetail"] = languageID.ToString();//để giữ languageID từ Func AlbumDetail đến Func DeleteAlbumImage.
            ViewData["ImageList"] = DataSingleton.GetAlbumModels().GetAlbumImages(albumID);
            return View("/Views/Backend/Album/AlbumDetail.aspx", DataSingleton.GetAlbumModels().GetAlbumByAlbumIDAndLanguageID(albumID, languageID));
        }

        /// <summary>
        /// upload image to folder image of album, and insert record to sql DB.
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="fileToUpload"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult InsertAlbumImage(int albumID, IEnumerable<HttpPostedFileBase> fileToUpload, String languageID)
        {
            HttpPostedFileBase aa = fileToUpload.ElementAt(0);
            if (fileToUpload.ElementAt(0) != null)
            {
                DataSingleton.GetAlbumModels().UploadImageAlbumDetail(albumID, fileToUpload, Path.Combine(Request.PhysicalApplicationPath.ToString(), "Image/Album/"));
            }
            ViewData["ImageList"] = DataSingleton.GetAlbumModels().GetAlbumImages(albumID);
            return View("/Views/Backend/Album/AlbumDetail.aspx",   DataSingleton.GetAlbumModels().GetAlbumByAlbumIDAndLanguageID(albumID, languageID));
        }

        [Authorize(Roles = ConstantClass.autAlbum)]
        public ActionResult DeleteAlbumImage(int imageID, int albumID)
        {
            string languageID = Session["LanguageID_AlbumDetail"].ToString();//lấy giá trị languageID từ Func AlbumDetail
            Session.Remove("LanguageID_AlbumDetail");
            DataSingleton.GetAlbumModels().AlbumImageDelete(imageID, Path.Combine(Request.PhysicalApplicationPath.ToString(), "Image/Album/album-" + albumID));
            ViewData["ImageList"] = DataSingleton.GetAlbumModels().GetAlbumImages(albumID); 

            return RedirectToAction("AlbumDetail", "Album", new { albumID = albumID, languageID = languageID});
        }
   #endregion

      
//////////////////////////////////////////////////////////////////////

     
  #region FrontEnd_Album

        public ActionResult Frontend_AlbumList(string albumMenu_SEO_URL,string pageIndex)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            int AlbumMenuID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(albumMenu_SEO_URL);
           // ViewData["SiteMapPathUserControl"] = DataSingleton.GetMenuListModels().BuildSiteMapPath(ConstantClass._Frontend_Album_MenuID, languageID);
            ViewData["albumMenuID_Temp"] = AlbumMenuID;
            ViewData["pageIndex"] = pageIndex;
            return View("/Views/Frontend/Album/AlbumList.aspx");
        }

        [ChildActionOnly]
        public ActionResult Frontend_AlbumList_Middle(String albumMenuID,String pageIndex)
            {

                string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
                ViewData["albumMenu_SEO_URL"] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(
                    albumMenuID, languageID);

                //string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
                //ViewData["albumMenu_SEO_URL"] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(
                //    ConstantClass._Frontend_Album_MenuID.ToString(), languageID);

                if (ViewData["albumMenu_SEO_URL"] != null)
                {
                    ////////////////////////// start paging
                    int totalRows = DataSingleton.GetAlbumModels().Frontend_GetTotalRowsOneLanguage(languageID);
                    int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.AlbumPageStep);

                    if (pageIndex != "1")
                    {
                        ViewData["Previous_Mark_Visibility"] = "true";
                    }
                    if (totalPages != Convert.ToInt16(pageIndex))
                    {
                        ViewData["Next_Mark_Visibility"] = "true";
                    }

                    ViewData["NextPageIndex"] = (Convert.ToInt16(pageIndex) + 1).ToString();
                    ViewData["PreviousPageIndex"] = (Convert.ToInt16(pageIndex) - 1).ToString();
                    ////////////////////////// end paging

                    return View("/Views/Frontend/Album/Middle.ascx", DataSingleton.GetAlbumModels().Frontend_GetOnePageAlbum(languageID, pageIndex, ConstantClass.AlbumPageStep));
                }
                else
                {
                    return View("/Views/Frontend/Album/Middle.ascx", null);
                }
            }

        public ActionResult Frontend_AlbumDetails(String album_SEO_URL)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
           // ViewData["SiteMapPathUserControl"] = DataSingleton.GetMenuListModels().BuildSiteMapPath(ConstantClass._Frontend_Album_MenuID, languageID);
            int albumID = DataSingleton.GetAlbumModels().GetAlbumID_By_SEO_URL(album_SEO_URL);
            if (albumID != 0)
            {
                AlbumView albumView_Temp = DataSingleton.GetAlbumModels().GetAlbumByAlbumIDAndLanguageID_Frontend(Convert.ToInt16(albumID), languageID);

                if (albumView_Temp == null)
                {
                    ViewData["AlbumName"] = "";
                }
                else
                {
                    ViewData["AlbumName"] = albumView_Temp.AlbumTitle;
                }

                ViewData["languageID"] = languageID;
                ViewData["albumID"] = albumID;
                return View("/Views/Frontend/Album/AlbumDetails.aspx", DataSingleton.GetAlbumModels().GetAlbumImages(albumID));
            }
            else
            {
                ViewData["AlbumName"] = "";
                return View("/Views/Frontend/Album/AlbumDetails.aspx", null);
            }
        }

        public ActionResult Frontend_AlbumDetails2(int albumID, String languageID)
        {
            string url = "/" + languageID + "/albde/";
            string albumMenu_SEO_URL = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(
                ConstantClass._Frontend_Album_MenuID.ToString(), languageID);
            string album_SEO_URL = DataSingleton.GetAlbumModels().GetAlbumSEO_URL_By_AlbumID_LanguageID(albumID, languageID);
            url += albumMenu_SEO_URL + "/" + album_SEO_URL;

            return Redirect(url);
        }

   #endregion
    }
}
